package util;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import net.sf.json.JSONArray;
import bean.EasyUiTreeBean;
import bean.MenuBean;

/**
 * 首页菜单的工具类
 * 
 * @author gj
 * 
 */
public class BuildMenuUtil {

	private static List<EasyUiTreeBean> buildMenuToList(List<MenuBean> menuList, int parentModuleMenuId) {
		List<EasyUiTreeBean> treeList = new ArrayList<EasyUiTreeBean>();
		for (MenuBean MenuBean : menuList) {
			if (MenuBean.getPid() == parentModuleMenuId) {
				buildTree(treeList, MenuBean);
			}
		}
		return treeList;
	}

	public static String buildMenuListToJsonString(List<MenuBean> menuList) {
		List<EasyUiTreeBean> treeList = new ArrayList<EasyUiTreeBean>();
		for (MenuBean MenuBean : menuList) {
			buildTree(treeList, MenuBean);
		}
		return JSONArray.fromObject(treeList).toString();
	}

	private static void buildTree(List<EasyUiTreeBean> treeList, MenuBean MenuBean) {
		EasyUiTreeBean treeNode = new EasyUiTreeBean();
		treeNode.setId(MenuBean.getId());
		treeNode.setText(MenuBean.getText());
		Map<String, String> attributesMap = new ConcurrentHashMap<String, String>();
		attributesMap.put("url", MenuBean.getUrl());
		treeNode.setAttributes(attributesMap);
		treeList.add(treeNode);
	}

	/**
	 * 构建首页左侧菜单
	 * 
	 * @param menuList
	 * @return
	 */
	public static Map<String, List<EasyUiTreeBean>> buildIndexLeftMenu(List<MenuBean> menuList) {
		Map<String, List<EasyUiTreeBean>> parentMenu = new LinkedHashMap<String, List<EasyUiTreeBean>>();
		for (MenuBean MenuBean : menuList) {
			if (MenuBean.getPid() == 0) {
				parentMenu.put(MenuBean.getText(), buildMenuToList(menuList, MenuBean.getId()));
			}
		}
		return parentMenu;
	}
}
